package com.ws.core.handle;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by WS on 2018/1/25.
 * 枚举类型与Mybatis 数据库类型互相转换
 */
public class BaseEnumTypeHandler extends BaseTypeHandler<BaseEnum> {
    private Class<BaseEnum> type;

    public BaseEnumTypeHandler(Class<BaseEnum> type) {
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException {
        if (parameter.getCode() instanceof Integer || parameter.getCode() instanceof Short || parameter.getCode() instanceof Byte){
            ps.setInt(i, (Integer) parameter.getCode());
        }
        if(parameter.getCode() instanceof String || parameter.getCode() instanceof Character){
            ps.setString(i, (String) parameter.getCode());
        }
    }

    @Override
    public BaseEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String constant = rs.getString(columnName);
        return rs.wasNull()? null: this.convert(constant);
    }

    @Override
    public BaseEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String constant = rs.getString(columnIndex);
        return rs.wasNull()? null: this.convert(constant);
    }

    @Override
    public BaseEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String constant = cs.getString(columnIndex);
        return cs.wasNull()? null: this.convert(constant);
    }

    private BaseEnum convert(String constant){
        BaseEnum[] baseEnums = this.type.getEnumConstants();
        for (BaseEnum baseEnum : baseEnums) {
            if (constant.equals(baseEnum.getCode())){
                return baseEnum;
            }
        }
        return null;
    }
}
